﻿using System;
using System.Reflection;
using System.ServiceModel;
using System.Windows.Forms;
using DevExpress.XtraBars.Alerter;
using DevExpress.XtraEditors;
using FileManager_Client.BusinessLogic;
using FileManager_Client.BusinessLogic.NotifyMessageService;
using FileManager_Client.PresentationLayer.Properties;
using FileManager_Client.Utility;
using System.Linq;

namespace FileManager_Client.PresentationLayer.NewUi
{
    public partial class FileManagerMain : BaseForm, INotifyMessage_ServiceCallback
    {
        private LoginForm _loginForm;
        private FileManager_Form _fileManagerForm;
        private AlertControl alertControl;
        private NotifyMessage_ServiceClient _notifyMessageService;
        private UserLoginResult _userLoginResult;
        public FileManagerMain(LoginForm loginForm)
        {
            InitializeComponent();
            _loginForm = loginForm;
            //双工通讯
            var instance = new InstanceContext(this);
            _notifyMessageService = new NotifyMessage_ServiceClient(instance);
            CacheGlobal.Add(GlobalString.System_Config_String.Wcf_NotifyServiceCacheKey, _notifyMessageService);
            var userSession =
                CacheGlobal.GetCache(GlobalString.System_Config_String.UserSession) as
                BusinessLogic.FileManagerUserService.UserLoginResult;
            var subScriberArgs = new UserLoginResult
            {
                CellPhonek__BackingField = userSession.CellPhonek__BackingField,
                CompanyIdk__BackingField = userSession.CompanyIdk__BackingField,
                DiskLargek__BackingField = userSession.DiskLargek__BackingField,
                Dutyk__BackingField = userSession.Dutyk__BackingField,
                Emailk__BackingField = userSession.Emailk__BackingField,
                ExtensionData = userSession.ExtensionData,
                LoginIdk__BackingField = userSession.LoginIdk__BackingField,
                OrderNumberk__BackingField = userSession.OrderNumberk__BackingField,
                PeopleNamek__BackingField = userSession.PeopleNamek__BackingField,
                Sexk__BackingField = userSession.Sexk__BackingField,
                Sidk__BackingField = userSession.Sidk__BackingField,
                UserIdk__BackingField = userSession.UserIdk__BackingField
            };
            _userLoginResult = subScriberArgs;
            _notifyMessageService.Subscriber(subScriberArgs);
            _fileManagerForm = new FileManager_Form();
            _fileManagerForm.Show();
            alertControl = new AlertControl
            {
                ShowToolTips = true,
                ShowCloseButton = true,
                AutoFormDelay = 7000,
                ControlBoxPosition = AlertFormControlBoxPosition.Top,
                FormDisplaySpeed = AlertFormDisplaySpeed.Moderate,
                FormLocation = AlertFormLocation.BottomRight,
                FormShowingEffect = AlertFormShowingEffect.SlideHorizontal,
                FormMaxCount = 12,
            };
        }

        public void NotifyFileMessage(string message)
        {
            try
            {
                var alertInfo = new AlertInfo("服务器消息", message) { Image = Resources.NitifyMessageTitle };
                alertControl.Show(this, alertInfo);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("异常信息:"+ex.Message, GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK,
                                      MessageBoxIcon.Information);
            }
        }

        public void NotifyFileMessageOpenFolder(NotifyMessageObject notifyMessageObject)
        {
            
        }

        public void UserLogOffMessage()
        {
            XtraMessageBox.Show(GlobalString.System_Exception_String.UserLogOffStr, GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK,
                                      MessageBoxIcon.Information);
            _notifyMessageService.UnSubscriber(_userLoginResult);
            Environment.Exit(0);
        }

        private void Tsmi_FileManager_Click(object sender, EventArgs e)
        {
            if (null != _fileManagerForm && !_fileManagerForm.IsDisposed)
            {
                _fileManagerForm.Show();
            }
        }

        private void Tsmi_SettingFileManager_Click(object sender, EventArgs e)
        {


        }

        private void Tsmi_SwithUser_Click(object sender, EventArgs e)
        {
            var logfinForm = new LoginForm(false);
            if (null != _fileManagerForm && !_fileManagerForm.IsDisposed)
                _fileManagerForm.Close();
            Close();
            _notifyMessageService.UnSubscriber(_userLoginResult);
            logfinForm.Show();
        }

        private void Tsmi_Logoff_Click(object sender, EventArgs e)
        {
                if (_fileManagerForm.UploadingFileCollection.Any(x => x.UploadingState == UploadingStateEnum.Uploading)
                    || _fileManagerForm._downloadingFileProgresses.Any(x => x.DownloadingState == DownloadingStateEnum.Downloading))
                    XtraMessageBox.Show("正在有文件上传或者下载，请先暂停再退出程序!", GlobalString.System_Config_String.MbxInfoStr,
                                        MessageBoxButtons.OK, MessageBoxIcon.Information);
            else
                {
                    _notifyMessageService.UnSubscriber(_userLoginResult);
                    Environment.Exit(Environment.ExitCode);    
                }
                
        }


        public void UserRepeatLoginLogOff()
        {
            foreach (var uploadFileProgress in _fileManagerForm.UploadingFileCollection)
            {
                _fileManagerForm.simpleButton_Click(uploadFileProgress.UploadButton, null);
            }
            foreach (var downloadingFileProgress in _fileManagerForm._downloadingFileProgresses)
            {
                _fileManagerForm.downloadingButton_Click(downloadingFileProgress.DownloadButton, null);
            }
            XtraMessageBox.Show(GlobalString.System_Exception_String.UserRepeatLogin, GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK,
                                      MessageBoxIcon.Information);
            Environment.Exit(0);
        }

        private void SystemNotifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (e.Button != MouseButtons.Left) return;
            if (null != _fileManagerForm && !_fileManagerForm.IsDisposed)
            {
                _fileManagerForm.Show();
            }
        }

        public void UpdateClientService(string version)
        {
            try
            {
                XtraMessageBox.Show("发现客户端新版本，请立即更新\r\nVersion:" + version, GlobalString.System_Config_String.MbxInfoStr, MessageBoxButtons.OK,
                                      MessageBoxIcon.Information);
                var userService = new UserService();
                var updateInfoResult = userService.GetLastVersion();
                var currentVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString();
                if (null != updateInfoResult && !updateInfoResult.ApplicationVersion.Equals(currentVersion, StringComparison.InvariantCulture))
                {
                    Invoke((EventHandler)delegate
                    {
                        Hide();
                        var updateForm = new UpdateInfomation(updateInfoResult);
                        updateForm.ShowDialog();
                    });
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("异常信息:" + ex.Message, GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK,
                                      MessageBoxIcon.Information);
            }
        }
    }
}